package com.itcase.JDBC_02.JDBCUtils;

import com.itcase.JDBC_01.JDBCDome.JDBCUtils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtil {
    //私有构造方法
    public JDBCUtil() {
    }

    //声明配置信息变量
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection con;

    //静态代码块中实现加载文件和注册驱动
    static {
        try {
            //通过流加载器返回配置文件的字节流
            InputStream res = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
            //创建properties集合,加载流对象的信息
            Properties pro = new Properties();
            pro.load(res);
            //获取信息为变量赋值
            driverClass = pro.getProperty("driverClass");
            url = pro.getProperty("url");
            username = pro.getProperty("username");
            password = pro.getProperty("password");
            // 注册驱动
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //获取数据库连接的方法
    public static Connection getConnection() {
        try {
            con = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
        //释放资源的方法
    public static void close(Connection  con, Statement stat, ResultSet rs){
        if (con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (stat!=null){
                try {
                    stat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                if (rs!=null){
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    public static void close(Connection con,Statement stat){
        close(con,stat,null);
    }
}
